import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:photo_view/photo_view.dart';
import 'package:photo_view/photo_view_gallery.dart';
import 'package:family_app/src/features/gallery/models/photo_model.dart';
import 'package:family_app/src/features/gallery/providers/gallery_provider.dart';

/// 照片查看页面
class PhotoViewScreen extends ConsumerStatefulWidget {
  final List<PhotoModel> photos;
  final int initialIndex;
  final String albumId;

  const PhotoViewScreen({
    Key? key,
    required this.photos,
    required this.initialIndex,
    required this.albumId,
  }) : super(key: key);

  @override
  ConsumerState<PhotoViewScreen> createState() => _PhotoViewScreenState();
}

class _PhotoViewScreenState extends ConsumerState<PhotoViewScreen> {
  late PageController _pageController;
  late int _currentIndex;
  bool _isFullScreen = false;

  @override
  void initState() {
    super.initState();
    _currentIndex = widget.initialIndex;
    _pageController = PageController(initialPage: _currentIndex);
  }

  @override
  void dispose() {
    _pageController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      appBar: _isFullScreen
          ? null
          : AppBar(
              backgroundColor: Colors.black,
              foregroundColor: Colors.white,
              title: Text(
                '${_currentIndex + 1}/${widget.photos.length}',
              ),
              actions: [
                IconButton(
                  icon: const Icon(Icons.delete),
                  onPressed: () => _showDeleteDialog(context),
                ),
                IconButton(
                  icon: const Icon(Icons.share),
                  onPressed: () {
                    // 分享功能实现
                    ScaffoldMessenger.of(context).showSnackBar(
                      const SnackBar(content: Text('分享功能开发中')),
                    );
                  },
                ),
              ],
            ),
      body: GestureDetector(
        onTap: () {
          setState(() {
            _isFullScreen = !_isFullScreen;
          });
        },
        child: Stack(
          children: [
            PhotoViewGallery.builder(
              scrollPhysics: const BouncingScrollPhysics(),
              builder: (BuildContext context, int index) {
                final photo = widget.photos[index];
                return PhotoViewGalleryPageOptions(
                  imageProvider: photo.localPath != null
                      ? FileImage(File(photo.localPath!))
                      : (photo.url != null && photo.url!.isNotEmpty
                          ? NetworkImage(photo.url!) as ImageProvider
                          : const AssetImage('assets/images/placeholder.png')
                              as ImageProvider),
                  initialScale: PhotoViewComputedScale.contained,
                  minScale: PhotoViewComputedScale.contained * 0.8,
                  maxScale: PhotoViewComputedScale.covered * 2,
                  heroAttributes: PhotoViewHeroAttributes(tag: photo.id),
                );
              },
              itemCount: widget.photos.length,
              loadingBuilder: (context, event) => Center(
                child: SizedBox(
                  width: 20.0,
                  height: 20.0,
                  child: CircularProgressIndicator(
                    value: event == null
                        ? 0
                        : event.cumulativeBytesLoaded /
                            event.expectedTotalBytes!,
                  ),
                ),
              ),
              backgroundDecoration: const BoxDecoration(color: Colors.black),
              pageController: _pageController,
              onPageChanged: (index) {
                setState(() {
                  _currentIndex = index;
                });
              },
            ),
            if (!_isFullScreen)
              Positioned(
                bottom: 0,
                left: 0,
                right: 0,
                child: Container(
                  padding:
                      const EdgeInsets.symmetric(vertical: 16, horizontal: 16),
                  decoration: BoxDecoration(
                    gradient: LinearGradient(
                      begin: Alignment.bottomCenter,
                      end: Alignment.topCenter,
                      colors: [
                        Colors.black.withOpacity(0.7),
                        Colors.transparent,
                      ],
                    ),
                  ),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      if (widget.photos[_currentIndex].name != null)
                        Text(
                          widget.photos[_currentIndex].name!,
                          style: const TextStyle(
                              color: Colors.white, fontSize: 16),
                        ),
                      if (widget.photos[_currentIndex].takenAt != null)
                        Text(
                          _formatDate(widget.photos[_currentIndex].takenAt!),
                          style: const TextStyle(
                              color: Colors.white70, fontSize: 14),
                        ),
                    ],
                  ),
                ),
              ),
          ],
        ),
      ),
    );
  }

  /// 显示删除确认对话框
  void _showDeleteDialog(BuildContext context) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('删除照片'),
        content: const Text('确定要删除这张照片吗？此操作不可恢复。'),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () async {
              final photoId = widget.photos[_currentIndex].id;
              Navigator.of(context).pop();
              final success = await ref
                  .read(albumOperationProvider.notifier)
                  .deletePhoto(widget.albumId, photoId);
              if (success) {
                if (mounted) {
                  Navigator.of(context).pop();
                }
              }
            },
            style: TextButton.styleFrom(foregroundColor: Colors.red),
            child: const Text('删除'),
          ),
        ],
      ),
    );
  }

  /// 格式化日期
  String _formatDate(DateTime dateTime) {
    return '${dateTime.year}-${dateTime.month.toString().padLeft(2, '0')}-${dateTime.day.toString().padLeft(2, '0')} ${dateTime.hour.toString().padLeft(2, '0')}:${dateTime.minute.toString().padLeft(2, '0')}';
  }
}
